package net

import (
	"common/biz"
	"common/config"
	"common/logs"
	"common/resp"
	"common/ut"
	"connector/game"
	"connector/models/request"
	"context"
	"core/entity"
	"core/service"
	"encoding/json"
	"gate/jwts"
	"time"
)

type EntryHandler struct {
	*service.UserService
}

func NewEntryHandler(userService *service.UserService) *EntryHandler {
	return &EntryHandler{
		userService,
	}
}

func (h *EntryHandler) Entry(session *Session, body []byte) (any, error) {
	logs.Debug("========================= Entry Start ========================================")
	logs.Debug("entry request param:%v", string(body))
	logs.Debug("========================= Entry End ========================================")
	// 1. 解析参数
	var entry request.EntryRequest
	if err := json.Unmarshal(body, &entry); err != nil {
		return resp.F(biz.RequestDataError), nil
	}
	// 2. 校验 Token
	uid, err := jwts.ParseToken(entry.Token, config.Conf.Jwt.Secret)
	if err != nil {
		return resp.F(biz.TokenInfoError), nil
	}
	// 3. 去 Mongo 查询用户
	user, err := h.UserService.FindUserByUid(context.TODO(), uid)
	if err != nil {
		return nil, err
	}
	// 4. 用户不存在，注册一个
	if user == nil {
		info := entry.UserInfo
		now := time.Now().UnixMilli()
		user = &entity.User{
			Uid:           uid,
			Gold:          int64(game.Conf.GameConfig["startGold"]["value"].(float64)), // 金币数
			Avatar:        ut.GetOrDefault(info.Avatar, "Common/head_icon_default"),
			Nickname:      ut.GetOrDefault(info.Nickname, "继续练习两年半 "+uid),
			Sex:           info.Sex,
			CreateTime:    now,
			LastLoginTime: now,
		}
		if err := h.UserService.Save(context.TODO(), user); err != nil {
			return nil, err
		}
	}
	session.Uid = uid
	return resp.S(map[string]any{
		"userInfo": user,
		"config":   game.Conf.GetFrontGameConfig(),
	}), nil
}
